package com.bdjk.bdmw.InfoGath.common.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.bdjk.bdmw.InfoGath.common.constants.JdbcConstants;
import com.bdjk.bdmw.InfoGath.exception.BusinessException;

public class JdbcUtil {

	/**
	 * 日志类
	 */
	//private final Logger log = LoggerFactory.getLogger(JdbcUtil.class);
	
	private static JdbcUtil instance = new JdbcUtil();

	/** 连接池  */
	private static List<Connection> connPool = new ArrayList<Connection>();
	
	/** 连接池数量  */
	private static int connSize = 20;
	
	private JdbcUtil() {
	}

	public static JdbcUtil getSingleInstance() {
		return instance;
	}

	
	static {
		try {
			Class.forName(JdbcConstants.DRIVER_CLASSNAME);
			Connection conn = null;
			for(int i = 0 ; i < connSize ; i++){
				conn = DriverManager.getConnection(JdbcConstants.URL, JdbcConstants.USERNAME,
						JdbcConstants.PASSWORD);
				connPool.add(conn);
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取链接
	 * 
	 * @return
	 * 
	 */
	public synchronized Connection getConnection() throws BusinessException {
		if(connPool.size() > 0){
			Connection connection = connPool.get(connPool.size() - 1);
			connPool.remove(connection);
			return connection;
		} else {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 释放连接
	 * 
	 * @param conn
	 */
	public synchronized void releaseConnection(Connection conn, PreparedStatement pstmt, ResultSet rs){
		try {
			if(null != conn){
				connPool.add(conn);
				this.notifyAll();
			}
			if (null != pstmt) {
				pstmt.close();
				pstmt = null;
			}
	
			if (null != rs) {
				rs.close();
				rs = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			//log.error(e.getStackTrace().toString());
		}
	}
	
	
	/**
	 * 关闭各种流
	 * 
	 * @param conn
	 * @param pstmt
	 * @param rs
	 */
	public void closeConnection(Connection conn, PreparedStatement pstmt, ResultSet rs)
			throws BusinessException {
		try {

			if (null != conn) {
				conn.close();
				conn = null;
			}
			if (null != pstmt) {
				pstmt.close();
				pstmt = null;
			}

			if (null != rs) {
				rs.close();
				rs = null;
			}

		} catch (SQLException e) {
			e.printStackTrace();
			//log.error(e.getStackTrace().toString());
		}
	}
	
	public static void main(String[] args) {
		try {
			Class.forName(JdbcConstants.DRIVER_CLASSNAME);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
